const router = require('koa-router')();
const upload = require('../utils/UploadService');
const logger = require('../utils/logHelper').helper;
const moment = require('moment');
/**
 * @api {post} /Upload 上传缓存图片
 * @apiGroup Upload
 * @apiName Upload
 * @apiParam {String} token
 */
router.post('/Upload', upload.uploadloc().single('file'), async (ctx) => {
    logger.startLog('/Upload', ctx.req.file.filename);
    let result;
    try {
        if (ctx.req.file.filename) {
            result = {
                code: 1,
                msg: "上传成功",
                data: 'http://127.0.0.1:3000/imgData/' + moment().format('YYYYMMDD') + '/' + ctx.req.file.filename
            };
            logger.endLog(result);
            ctx.body = result;
        }
        else {
            result = {code: 0, msg: "上传失败"};
            logger.endLog(result);
            ctx.body = result;
        }
    } catch (e) {
        result = {code: 0, msg: e.message};
        logger.endErrLog(result);
        ctx.body = result;
    }
});
/**
 * @api {post} /UploadNew 上传缓存图片
 * @apiGroup Upload
 * @apiName UploadNew
 * @apiParam {String} token
 */
router.post('/UploadNew', upload.UploadNew().single('file'), async (ctx) => {
    logger.startLog('/UploadNew', ctx.req.file.filename);
    let result;
    try {
        if (ctx.req.file.filename) {
            result = {code: 1, msg: "上传成功", data: 'http://127.0.0.1:3000/images/New/' + ctx.req.file.filename};
            logger.endLog(result);
            ctx.body = result;
        }
        else {
            result = {code: 0, msg: "上传失败"};
            logger.endLog(result);
            ctx.body = result;
        }
    } catch (e) {
        result = {code: 0, msg: e.message};
        logger.endErrLog(result);
        ctx.body = result;
    }
});

/**
 * @api {post} /RemoveNew 删除实时新闻图片
 * @apiGroup Upload
 * @apiName RemoveNew
 * @apiParam {String} FileName
 */
router.post('/RemoveNew', async (ctx) => {
    let data = ctx.request.body;
    if (!data.FileName) {
        ctx.body = {code: 0, msg: '参数不齐'};
        return
    }
    logger.startLog('/RemoveNew', data);
    let result;
    try {
        let res=await upload.RemoveNew('./public/images/New/'+data.FileName);
        if (res.code==='1') {
            result = {code: 1, msg: "删除成功"};
            logger.endLog(result);
            ctx.body = result;
        }
        else {
            result = {code: 0, msg: "删除失败"};
            logger.endLog(result);
            ctx.body = result;
        }
    } catch (e) {
        result = {code: 0, msg: e.message};
        logger.endErrLog(result);
        ctx.body = result;
    }
});

module.exports = router;